<template>
  <el-dialog
    :title="title"
    v-model="visible"
    width="420px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-form 
      ref="formRef" 
      :model="form" 
      :rules="rules" 
      label-width="100px"
    >
      <el-form-item label="学号" prop="studentId">
        <el-input v-model="form.studentId" placeholder="请输入学号"></el-input>
      </el-form-item>
      
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      
      <el-form-item label="队次" prop="classId">
        <el-select 
          v-model="form.classId" 
          placeholder="选择队次" 
          filterable 
          style="width: 100%;"
        >
          <el-option 
            v-for="lcClass in lcClasses" 
            :key="lcClass.id" 
            :label="lcClass.name" 
            :value="lcClass.id">
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="专业" prop="majorId">
        <el-select 
          v-model="form.majorId" 
          placeholder="选择专业" 
          filterable 
          style="width: 100%;"
        >
          <el-option 
            v-for="major in majors" 
            :key="major.id" 
            :label="major.name" 
            :value="major.id">
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="培养层次" prop="cengCiId">
        <el-select 
          v-model="form.cengCiId" 
          placeholder="选择培养层次" 
          filterable 
          style="width: 100%;"
        >
          <el-option 
            v-for="cengCi in cengCis" 
            :key="cengCi.id" 
            :label="cengCi.name" 
            :value="cengCi.id">
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="状态" prop="statusId">
        <el-select 
          v-model="form.statusId" 
          placeholder="选择状态" 
          style="width: 100%;"
        >
          <el-option 
            v-for="status in studentStatuses" 
            :key="status.id" 
            :label="status.name" 
            :value="status.id">
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="是否留级" prop="isRepeater">
        <el-switch v-model="form.isRepeater"></el-switch>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch, nextTick } from 'vue'

export default {
  name: 'StudentEditDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '学生表单'
    },
    student: {
      type: Object,
      default: null
    },
    lcClasses: {
      type: Array,
      default: () => []
    },
    majors: {
      type: Array,
      default: () => []
    },
    cengCis: {
      type: Array,
      default: () => []
    },
    studentStatuses: {
      type: Array,
      default: () => []
    }
  },
  emits: ['update:modelValue', 'submit', 'cancel'],
  setup(props, { emit }) {
    const formRef = ref(null)
    const visible = ref(false)
    
    const form = reactive({
      id: null,
      studentId: '',
      name: '',
      classId: '',
      majorId: '',
      cengCiId: '',
      statusId: '',
      isRepeater: false
    })

    // 表单验证规则
    const rules = {
      studentId: [
        { required: true, message: '请输入学号', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      classId: [
        { required: true, message: '请选择队次', trigger: 'change' }
      ],
      majorId: [
        { required: true, message: '请选择专业', trigger: 'change' }
      ],
      cengCiId: [
        { required: true, message: '请选择培养层次', trigger: 'change' }
      ],
      statusId: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    }

    // 监听visible变化
    watch(() => props.modelValue, (newValue) => {
      visible.value = newValue
    })

    watch(visible, (newValue) => {
      emit('update:modelValue', newValue)
    })

    // 强制重置表单数据的方法
    const forceResetForm = () => {
      form.id = null;
      form.studentId = '';
      form.name = '';
      form.classId = '';
      form.majorId = '';
      form.cengCiId = '';
      form.statusId = '';
      form.isRepeater = false;
    };

    // 监听学生数据变化
    watch(() => props.student, (newStudent) => {
      // 先强制重置表单
      forceResetForm();
      
      if (newStudent) {
        // 编辑模式
        form.id = newStudent.id
        form.studentId = newStudent.studentId
        form.name = newStudent.name
        form.classId = newStudent.classId
        form.majorId = newStudent.majorId
        form.cengCiId = newStudent.cengCiId
        form.statusId = newStudent.statusId
        form.isRepeater = newStudent.isRepeater || false
      } else {
        // 新增模式，设置默认状态为"在读"
        const inSchoolStatus = props.studentStatuses.find(status => status.name === '在读')
        if (inSchoolStatus) {
          form.statusId = inSchoolStatus.id
        }
      }

      // 清除验证错误
      nextTick(() => {
        formRef.value && formRef.value.clearValidate()
      })
    }, { immediate: true })
    
    const handleSubmit = () => {
      if (!formRef.value) return
      
      formRef.value.validate((valid) => {
        if (valid) {
          emit('submit', { ...form })
        }
      })
    }

    const handleCancel = () => {
      visible.value = false
    }

    const handleClosed = async () => {
      // 强制重置表单数据
      forceResetForm();
      
      await nextTick();
      if (formRef.value) {
        formRef.value.clearValidate();
      }
    };

    return {
      formRef,
      visible,
      form,
      rules,
      handleSubmit,
      handleCancel,
      handleClosed,
      forceResetForm
    }
  }
}
</script>

<style scoped>
/* 强制设置对话框宽度 */
:deep(.el-dialog) {
  width: 420px !important;
  max-width: 420px !important;
  min-width: 420px !important;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}

:deep(.el-dialog__footer) {
  padding-top: 0;
}
</style>